/*
  1.需要知道animationClip
  2.需要播放动画能力animation
*/

import { animation, AnimationClip, Sprite, SpriteFrame } from "cc";
import { PlayerStateMachine } from "../Scripts/Player/PlayerStateMachine";
import ResourceManager from "../Runtime/ResourceManager";
import { StateMachine } from "./StateMachine";
import { sortSpriteFrame } from "../Utils";

export const ANIMATION_SPEED=1/8

export default class State {
  private animationClip:AnimationClip

  constructor(
    private fsm: StateMachine,    // 所属状态机
    private path: string,         // 资源路径
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
    private speed:number=ANIMATION_SPEED,
    private events:any[]=[]
  ){
    this.init()
  }

  async init(){
    //解决异步
    const promise=ResourceManager.Instance.loadDir(this.path)
    this.fsm.waitingList.push(promise)
    const spriteFrames=await promise
    //
    this.animationClip = new AnimationClip();

    const track  = new animation.ObjectTrack();
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame');
    const frames: Array<[number, SpriteFrame]> =sortSpriteFrame(spriteFrames).map((item, index) =>[index * this.speed, item]);
    track.channel.curve.assignSorted(frames);

    this.animationClip.addTrack(track);
    this.animationClip.name=this.path // 用路径命名，保证唯一性
    this.animationClip.duration = frames.length*this.speed;
    this.animationClip.wrapMode = this.wrapMode

    for(const event of this.events){
      this.animationClip.events.push(event)
    }

    this.animationClip.updateEventDatas();
  }

  run(){
    if(this.fsm.animationComponent?.defaultClip?.name===this.animationClip.name){
      return
    }
    // 将动画剪辑设置为动画组件的默认剪辑
    this.fsm.animationComponent.defaultClip=this.animationClip
    // 开始播放动画
    this.fsm.animationComponent.play()
  }
}
